package cn.qiyu5522.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.constant.SystemConstants;
import cn.qiyu5522.domain.entity.LoginUser;
import cn.qiyu5522.domain.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * ClassName: LoginUserUtils
 * Package: cn.qiyu5522.utils
 * Description:
 *
 * @Author: Tonkey
 * @Create：2024/4/13-20:34
 * @Version: v1.0
 */
public class SecurityUtils {


    private SecurityUtils(){

    }

    /**
     *  获取用户信息
     * @return
     */
    public static User getUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = new LoginUser();
        if(ObjectUtil.isNotEmpty(authentication)) {
            if (authentication.getPrincipal() instanceof LoginUser) {
                loginUser = (LoginUser) authentication.getPrincipal();
                return loginUser.getUser();
            }
        }
        User user = new User();
        user.setId(1L);
        user.setUserName("sg");
        user.setNickName("tonkey");
        loginUser.setUser(user);
        return  loginUser.getUser();
    }

    /**
     * 获取 登录用户的ID
     * @return
     */
    public static Long getLoginUserId(){
        return getUser().getId();
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    public static boolean isAdmin() {
        return SystemConstants.SUPER_ADMINISTER_USER_ID.equals(SecurityUtils.getUser().getId());
    }

    public static LoginUser getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser;
    }
}
